package com.e3.basdoc.cust.dao;

import java.util.ArrayList;
import java.util.List;

import com.e3.basdoc.cust.entity.CustEntity;
import com.e3.basdoc.cust.model.CustModel;
import com.e3.basdoc.cust.model.CustQC;
import com.e3.core.base.SuperDAO;

public class CustDAO extends SuperDAO {

	private String querySQL = "SELECT t FROM CustEntity t";

	public List<CustEntity> getCustsByCondition(CustQC custQC) {
		String sql = querySQL;
		custQC.setPrefix("t");
		String whereSQL = custQC.getWhereSQL();
		if (whereSQL != null && whereSQL.length() > 0) {
			sql = sql + " WHERE " + whereSQL;
		}
		return this.find(sql);
	}

	public void deleteCustByCodes(List<CustModel> custModels) {
		if (custModels == null || custModels.isEmpty()) {
			return;
		}
		String[] codes = new String[custModels.size()];
		for (int i = 0; i < custModels.size(); i++) {
			codes[i] = custModels.get(i).getCode();
		}
		this.deleteAllBySingleField(CustEntity.class, "code", codes);
	}

	public void deleteCustByIds(Long[] ids) {
		this.deleteAllBySingleField(CustEntity.class, "id", ids);
	}

	public void deleteCustChildren(Long[] parentIds) {
		if (parentIds == null || parentIds.length == 0) {
			return;
		}
		this.deleteAllBySingleField(CustEntity.class, "parentId", parentIds);
	}

	public CustEntity getCustByCode(String code) {
		String whSql = " WHERE t.code = ?";
		String sql = querySQL + whSql;
		List<CustEntity> entities = this.find(sql, code);
		return (entities == null || entities.size() == 0) ? null : entities.get(0);
	}

	public long childrenCount(long pId) {
		String sql = "SELECT count(t) FROM CustEntity t WHERE t.parentId = ?";
		return this.counter(sql, pId);
	}
	
	public long counterByCondition(CustQC qc){
		String sql = "SELECT count(t) FROM CustEntity t";
		if(qc!=null){
			qc.setPrefix("t");
			String whereSQL = qc.getWhereSQL();
			if (whereSQL != null && whereSQL.length() > 0) {
				sql = sql + " WHERE " + whereSQL;
			}
		}
		
		return this.counter(sql);
	}
	
	@SuppressWarnings("rawtypes")
	public List<Long> getPagingCustIdsByCondition(CustQC qc,int start,int max) {
		String sql = "SELECT t.id FROM CustEntity t";
		if(qc != null){
			qc.setPrefix("t");
			String whereSQL = qc.getWhereSQL();
			if (whereSQL != null && whereSQL.length() > 0) {
				sql = sql + " WHERE " + whereSQL;
			}
		}
		List result = executePagingHQLQuery(sql, null,start,max);
		if(result!=null){
			List<Long> ids = new ArrayList<Long>(result.size());
			for (Object object : result) {
				ids.add((Long)object);
			}
			return ids;
		}
		return null;
	} 


}
